
import subprocess
import os
import sys

# 设置Windows共享信息
share_username = "hexq"
share_password = "110"
share_server = "192.168.110.109"
share_folder = "hxq"

# 构建UNC路径
server_path = f"\\\\{share_server}\\{share_folder}"
local_path = f"e:\\hxq"
# 使用net use命令进行访问
command = f"net use {server_path} /user:{share_username} {share_password}"
subprocess.run(command, shell=True)


# 遍历下载最新的word文件
try:
    # 获取源目录中所有word文件的路径和修改时间
    #用列表解析代替下面的循环
    remotedocfile = [(os.path.join(server_path, filename), os.path.getmtime(os.path.join(server_path, filename))) for filename in os.listdir(server_path) if (filename.endswith('.doc') or filename.endswith('.docx')) and filename.startswith('重要气象信息')]
    # remotedocfile = []
    # for filename in os.listdir(server_path):
    #     if filename.endswith('.doc') or filename.endswith('.docx'):
    #         if filename.startswith('重要气象信息'):
    #             remotedocfile.append((os.path.join(server_path, filename),os.path.getmtime(os.path.join(server_path, filename))))

    # 获得最新的文件到变更时间
    if remotedocfile == []:
        print('没有合适的文档')
        sys.exit(1)
    else:
        # 根据修改时间对文件进行排序
        remotedoc = sorted(remotedocfile, key=lambda x: x[1], reverse=True)
        latest_remotefile = remotedoc[0][0]
        latest_remotefile_mtime = remotedoc[0][1]
        #找出本地文件的最新时间
        localdocfile = [(os.path.join(local_path, filename),os.path.getmtime(os.path.join(local_path, filename))) for filename in os.listdir(local_path)  if filename.endswith('.doc') | filename.endswith('.docx')]
        localdoc = sorted(localdocfile,key=lambda x: x[1], reverse=True)
        localfile = os.path.join(local_path, os.path.basename(latest_remotefile))

        # 如果服务器文件时间比本地新，复制最新的文件到本机目录
        if localdoc:
            latest_localfile_mtime = localdoc[0][1]
            if latest_remotefile_mtime > latest_localfile_mtime:
                print('现在复制', latest_remotefile, '...')
                shutil.copy2(latest_remotefile, localfile)
                print(os.path.basename(latest_remotefile), '已成功复制')
            else:
                print('文件没有更新')
                sys.exit(1)
        else:
            print('现在复制', latest_remotefile, '...')
            shutil.copy2(latest_remotefile, localfile)
            print(os.path.basename(latest_remotefile), '已成功复制')

except Exception as e:
    print("Error:", e)
    sys.exit(1)

finally:
    # 使用完毕后取消访问
    subprocess.run(f"net use {server_path} /delete", shell=True)